package tr.muyat.server.bt;

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

/**
 * 
 * @author fxulusoy
 */
public class RemoteBluetoothServer{

	public static void main(String[] args) {
		ServerThread waitThread = new ServerThread();
		waitThread.start();
	}
	
	/**
	 * 
	 * @author fxulusoy
	 */
	static class ServerThread extends Thread {

		/** Constructor */
		public ServerThread() {
		}

		@Override
		public void run() {
			// retrieve the local Bluetooth device object
			LocalDevice local = null;

			StreamConnectionNotifier notifier;
			StreamConnection connection = null;

			// setup the server to listen for connection
			try {
				local = LocalDevice.getLocalDevice();
				System.out.println("Name: " + local.getFriendlyName());
				local.setDiscoverable(DiscoveryAgent.GIAC);

				UUID uuid = new UUID(89087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
				//uuid = new UUID("14c6093b00001000800000805f9b34f0", false);
				//uuid = new UUID("0000110100001000800000805f9b34fb", false);
				//uuid = new UUID("0000000030001000800000805f9b34fb", false);
				uuid = new UUID("fa87c0d0afac11de8a390800200c9a66", false);
				
				String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
				System.out.println("Starting the service : " + url);
				notifier = (StreamConnectionNotifier)Connector.open(url);
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
	       	// waiting for connection
			while(true) {
				try {
					System.out.println("waiting for connection...");
					// Blocking function call.It is blocked until a request comes.
					connection = notifier.acceptAndOpen();

					ProcessConnectionThread processThread = new ProcessConnectionThread(connection);
					processThread.start();
				} catch (Exception e) {
					e.printStackTrace();
					return;
				}
			}
		}
	}
	
}


